/**
 * Created by user on 2018/3/7.
 */
import SocketManager from './utils/SocketManager'
import {
  getStamp,
  getSeq,
  MessageCenter,
  formatSocketMsg,
  Type,
  VoicePlayer,
  VideoPlayer,
  cloneObj
} from './utils/Global'
import GlobalTime from './utils/GlobalTime'


class Manager {
  info = null
  options = {}
  socketManager = null
  messageListener = {}
  reConnectTimer = null
  onSocketNotice(msg) {
    if (msg.code === this.socketManager.errorCode.CON_LOSE.code) {
      this.messageListener.listenSocketStatus && this.messageListener.listenSocketStatus(false)
      this.reConnect()
    }
  }
  reConnect() {
    this.reConnectTimer && clearTimeout(this.reConnectTimer)
    this.socketManager.connect((res) => {
      if (res) {
        this.messageListener.listenSocketStatus && this.messageListener.listenSocketStatus(true)
      } else {
        setTimeout(() => {
          this.reConnect()
        }, 1 * 1000)
      }
    })
  }
  onSocketMessage(msg) {
    const m = formatSocketMsg(msg)
    if (m) {
      MessageCenter.addMessage(m)
    }
  }
  handleLiveSlideMsg(msg, callback) {
    this.messageListener.listenLiveSlide && this.messageListener.listenLiveSlide(msg, callback)
  }
  handleLiveVoiceMsg(msg, callback) {
    this.messageListener.listenLiveVoice && this.messageListener.listenLiveVoice(msg, callback)
  }
  handleLiveStartVideoMsg(msg, callback) {
    this.messageListener.listenLiveStartVideo && this.messageListener.listenLiveStartVideo(msg, callback)
  }
  handleMsg(type, msg, callback) {
    if (type === Type.COMMON_TYPE.COMMON_LIVE_SLIDE) {
      this.handleLiveSlideMsg(msg, callback)
    } else if (type === Type.COMMON_TYPE.COMMON_LIVE_VOICE) {
      this.handleLiveVoiceMsg(msg, callback)
    } else if (type === Type.COMMON_TYPE.COMMON_START_VIDEO){
      this.handleLiveStartVideoMsg(msg, callback)
    }
  }
  login(messageListener, callback) {
    this.messageListener = Object.assign({}, messageListener)
    var opt = {
      roomId: this.info.info.id
    }
    this.options = Object.assign({}, opt)
    const listeners = {
      onNotice: this.onSocketNotice.bind(this),
      onMessage: this.onSocketMessage.bind(this)
    }
    MessageCenter.setCallback(this.handleMsg.bind(this))
    MessageCenter.start()
    this.socketManager = new SocketManager(listeners)
    this.socketManager.login(this.options, callback)
  }
  initPage(info, callback) {
    this.info = info
    GlobalTime.setGlobalTime(this.info.timestamp)
    MessageCenter.setStartTime(info.info.create_time)
    const currentIndex = this.getCurrentIndex()
    const currentVideo = this.getCurrentVideo(currentIndex)
    if (currentVideo) {
      const _msg = {
        type: Type.COMMON_TYPE.COMMON_START_VIDEO,
        seq_time: getSeq(),
        timestamp: getStamp(),
        isDelay: true,
        data: currentVideo
      }
      MessageCenter.addMessage(_msg)
    }
    callback && callback(currentIndex)
  }
  getCurrentIndex() {
    var currentIndex = 0
    var lastImageMsg = this.info.last_image
    if (lastImageMsg) {
      var formatLastImageMsg = formatSocketMsg(lastImageMsg)
      if (formatLastImageMsg.type === Type.COMMON_TYPE.COMMON_LIVE_SLIDE) {
        currentIndex = formatLastImageMsg.data.index
      }
    }
    return currentIndex
  }
  getCurrentVideo(currentIndex) {
    var images = this.info.images
    var videos = this.info.videos
    var currentVideo = null
    const all_play_video_msg = (function(vs){
      var arr = []
      for (let i in vs) {
        var vsi = formatSocketMsg(vs[i])
        if (vsi) {
          arr.push(vsi)
        }
      }
      return arr
    })(videos || [])
    if (images[currentIndex] && images[currentIndex].is_video) {
      var lastVideo = all_play_video_msg[all_play_video_msg.length - 1]
      if (lastVideo && lastVideo.data.url === images[currentIndex].video_url) {
        var diff = getStamp() - lastVideo.timestamp
        if (diff < (images[currentIndex].video_time * 1000)) {
          currentVideo = {
            url: images[currentIndex].video_url,
            time: parseInt((diff / 1000).toFixed(2))
          }
        }
      }
    }
    return currentVideo
  }
}

window.manager = new Manager()
window.voicePlayer = VoicePlayer
window.videoPlayer = VideoPlayer
